<template>
  <div>
    <el-page-header @back="goBack" content="秒杀活动详情" style="color:#3198ff"></el-page-header>
    <div style="margin-top: 30px;">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="form-item">
            <span class="title">商品一级分类</span>
            <el-select v-model="param.tbSpu.cid1" placeholder="请选择" @change="fristGoodClick">
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="form-item">
            <span class="title">商品二级分类</span>
            <el-select v-model="param.tbSpu.cid2" placeholder="请选择">
              <el-option
                v-for="item in productOptions1"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="form-item">
            <span class="title">商品名称</span>
            <el-input placeholder="请输入名称" v-model="param.tbSpu.title"></el-input>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="form-item button-container">
            <el-button type="primary" @click="search" icon="el-icon-search">查询</el-button>
            <el-button type="primary" @click="resetSearchCotnet" icon="el-icon-refresh">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div style="margin-top: 50px;">
      <el-table
        ref="multipleTable"
        border
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :row-key="getRowKey"
        :tree-props="{children: 'skuList', hasChildren: 'hasChildren'}"
        v-loading="isLoading"
      >
        <el-table-column prop="title" label="商品SPU名称"></el-table-column>
        <el-table-column prop="skuTitle" label="商品SKU名称"></el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
        <el-table-column prop="price2" label="商品原价"></el-table-column>
        <el-table-column label="秒杀库存">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :min="0"
              :max="parseInt(scope.row.stock)"
              v-model="scope.row.seckillStock"
              :precision="0"
              :step="1"
              :controls="false"
              style="width:90%"
              @blur="handleInputBlurResult({index:scope.$index,result:scope.row})"
              @keyup.enter.native="handleInputBlurResult({index:scope.$index,result:scope.row})"
              v-if="scope.row.isParent =='0'"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="秒杀价格">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :min="0"
              :max="scope.row.price2"
              v-model="scope.row.skuPrice"
              :precision="2"
              :step="0.01"
              :controls="false"
              style="width:90%"
              @blur="pricehandleInputBlurResult({index:scope.$index,result:scope.row})"
              @keyup.enter.native="pricehandleInputBlurResult({index:scope.$index,result:scope.row})"
              v-if="scope.row.isParent =='0'"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="单人最多购买个数">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :min="0"
              :max="parseInt(scope.row.seckillStock)"
              v-model="scope.row.restrictNum"
              :precision="0"
              :step="1"
              :controls="false"
              style="width:90%"
              @blur="peoplehandleInputBlurResult({index:scope.$index,result:scope.row})"
              @keyup.enter.native="peoplehandleInputBlurResult({index:scope.$index,result:scope.row})"
              v-if="scope.row.isParent =='0'"
            ></el-input-number>
          </template>
        </el-table-column>
        <!-- <el-table-column type="selection" width="100" :reserve-selection="true" align="center"></el-table-column> -->
        <el-table-column fixed="right" label="选择" width="120">
          <template slot-scope="scope">
            <el-button
              style="margin-left:15px"
              @click="handleToAllSelect(scope.row)"
              size="small"
              v-if="scope.row.isParent =='1'"
            >全选</el-button>
            <el-button
              style="margin-left:15px"
              size="small"
              type="primary"
              plain
              v-if="scope.row.isParent =='0'"
              @click="handleToSelect(scope.row)"
            >{{scope.row.isChecked =='1' ? '取消选中' : '选中'}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @current-change="currentPageChange"
          layout="prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <div>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="form-item">
            <span class="title">
              <span style="color:#F56C6C">*</span>专场名称
            </span>
            <el-input placeholder="请输入" maxlength="50" v-model="seckillName"></el-input>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="form-item">
            <span class="title">
              <span style="color:#F56C6C">*</span>有效日期
            </span>
            <el-date-picker
              v-model="adddateList"
              type="datetimerange"
              value-format="yyyy-MM-dd HH"
              format="yyyy-MM-dd HH"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :clearable="false"
            ></el-date-picker>
          </div>
        </el-col>
      </el-row>

      <div style="text-align:center; margin-top: 50px;">
        <el-button type="primary" @click="submitForm()">修改</el-button>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "",
  data() {
    return {
      isLoading: true,
      productOptions: [],
      productOptions1: [],
      param: {
        tbSpu: {
          title: "", // 优惠券名称
          cid1: "", //类型
          cid2: "" //类型2
        },
        queryRequest: {
          pageNum: 1,
          pageSize: 10
        }
      },
      tableData: [],
      total: 1,
      multipleSelection: [], //商品选中集合
      seckillName: "", //专场名称
      adddateList: "", //有效时间
      sekillId: "",
      editTableIndex: [] //编辑的数据集合
    };
  },
  components: {},
  computed: {},
  beforeMount() {},
  mounted() {
    this.sekillId = this.$route.query.id;
    this.initData();
    this.goodFirst();
  },
  methods: {
    handleToAllSelect(scope) {
      console.log(scope);
      scope.skuList.forEach((item, index) => {
        scope.skuList[index].isChecked = "1";
        var indexs;
        var isCloud = false;
        this.editTableIndex.forEach((item2, index2) => {
          if (item.id == item2.id) {
            indexs =index2;
            isCloud = true;
          }
        });
        if (!isCloud) {
          this.editTableIndex.push(item);
        } else {
          this.editTableIndex[indexs].isChecked = "1";
        }
      });
    },
    handleToSelect(scope) {
      if (scope.isChecked == "1") {
        scope.isChecked = "0";
        this.editTableIndex.forEach((item, index) => {
          if (scope.id == item.id) {
            this.editTableIndex[index].isChecked = "0";
          }
        });
      } else {
        scope.isChecked = "1";
        for (let i = 0; i < this.editTableIndex.length; i++) {
          var item = this.editTableIndex[i];
          if (scope.id == item.id) {
            this.editTableIndex[i].isChecked = "1";
            return;
          }
        }
        this.editTableIndex.push(scope);
      }
    },
    // cellclass(row) {
    //   if (row.columnIndex === 7) {
    //     return "DisabledSelection";
    //   }
    // },
    getRowKey(row) {
      return row.id;
    },
    fristGoodClick(val) {
      this.param.tbSpu.cid2 = "";
      this.goodSecond(val);
    },
    goodFirst() {
      this.$service.firstGood().then(res => {
        if (res.code == "00000") {
          this.productOptions = res.data || [];
        }
      });
    },
    goodSecond(cid) {
      this.$service.secondGood(cid).then(res => {
        if (res.code == "00000") {
          this.productOptions1 = res.data || [];
        }
      });
    },
    goBack() {
      this.$router.back();
    },
    initData() {
      var id = this.sekillId;
      this.param.seckillId = id;
      var params = this.param;
      this.isLoading = true;
      this.$service.seckillDetail(this.param).then(res => {
        this.isLoading = false;
        if (res.code == "00000") {
          if (
            res.data.tbSpuList.records.length == 0 &&
            this.param.queryRequest.pageNum != 1
          ) {
            this.param.queryRequest.pageNum -= 1;
            this.initdata();
          }

          if (this.editTableIndex.length == 0) {
            var sekills = res.data.seckill;
            this.seckillName = sekills.name;
            this.adddateList = [
              sekills.startTime + ":00:00",
              sekills.endTime + ":00" + ":00"
            ];
            this.editTableIndex = res.data.seckillSkuList;
            res.data.seckillSkuList.forEach((item, index) => {
              this.editTableIndex[index].id = item.skuId;
              this.editTableIndex[index].skuPrice = item.seckillMoney2;
            });
          }
          this.tableData =
            (res.data.tbSpuList && res.data.tbSpuList.records) || [];
          this.total = res.data.tbSpuList.total || 1;
          //记忆编辑项
          for (let i = 0; i < this.tableData.length; i++) {
            const element = this.tableData[i].skuList;
            for (let j = 0; j < element.length; j++) {
              const items = element[j];
              for (let k = 0; k < this.editTableIndex.length; k++) {
                const item = this.editTableIndex[k];
                if (items.id == item.id) {
                  this.tableData[i].skuList[
                    j
                  ].seckillStock = this.editTableIndex[k].seckillStock;
                  this.tableData[i].skuList[j].skuPrice = this.editTableIndex[
                    k
                  ].skuPrice;
                  this.tableData[i].skuList[
                    j
                  ].restrictNum = this.editTableIndex[k].restrictNum;
                  this.tableData[i].skuList[j].isChecked = this.editTableIndex[
                    k
                  ].isChecked;
                }
              }
            }
          }
        }
      });
    },
    search() {
      this.param.queryRequest.pageNum = 1;
      this.initData();
    },
    resetSearchCotnet() {
      //重置搜索条件
      this.param.tbSpu.title = "";
      this.param.tbSpu.cid1 = "";
      this.param.tbSpu.cid2 = "";
    },
    handleSelectionChange(val) {
      this.multipleSelection = [];
      for (let i = 0; i < val.length; i++) {
        const element = val[i];
        this.multipleSelection.push(element);
      }
    },

    submitForm() {
      var param = {};
      param.seckillId = this.sekillId;
      if (this.seckillName == "") {
        this.$message({
          message: "请填写秒杀名称",
          type: "warning"
        });
        return;
      } else {
        param.name = this.seckillName;
      }
      if (this.adddateList.length > 0) {
        param.startTime = this.adddateList[0];
        param.endTime = this.adddateList[1];
      } else {
        this.$message({
          message: "请填写有效日期",
          type: "warning"
        });
        return;
      }
      if (param.startTime == param.endTime) {
        this.$message({
          message: "不能填写同一时间",
          type: "warning"
        });
        return;
      }
      this.multipleSelection = [];
      console.log("subeditTableIndex", this.editTableIndex);
      this.editTableIndex.forEach(item => {
        if (item.isChecked == "1") {
          this.multipleSelection.push(item);
        }
      });
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请选择要添加的商品",
          type: "warning"
        });
        return;
      } else {
        var SkuList = [];
        for (let j = 0; j < this.multipleSelection.length; j++) {
          const item = this.multipleSelection[j];
          var seckillItem = {
            spuId: item.spuId,
            skuId: item.id,
            seckillMoney: item.skuPrice * 100,
            seckillStock: item.seckillStock,
            restrictNum: item.restrictNum
          };
          SkuList.push(seckillItem);
        }

        param.seckillSkuList = SkuList;
      }
      this.$service.seckillUpdate(param).then(res => {
        if (res.code == "00000") {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.$router.back();
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
    },
    /**
     * 成绩输入回车/失去焦点统计
     * @param {Number} index 行索引
     * @param {Number} result 秒杀库存
     */
    handleInputBlurResult({ index, result }) {
      console.log(result);
      for (let i = 0; i < this.editTableIndex.length; i++) {
        var item = this.editTableIndex[i];
        if (result.id == item.id) {
          this.editTableIndex[i] = result;
          return;
        }
      }
      this.editTableIndex.push(result);

      console.log(this.editTableIndex);
    },
    pricehandleInputBlurResult({ index, result }) {
      for (let i = 0; i < this.editTableIndex.length; i++) {
        var item = this.editTableIndex[i];
        if (result.id == item.id) {
          this.editTableIndex[i] = result;
          return;
        }
      }
      this.editTableIndex.push(result);
    },
    peoplehandleInputBlurResult({ index, result }) {
      for (let i = 0; i < this.editTableIndex.length; i++) {
        var item = this.editTableIndex[i];
        if (result.id == item.id) {
          this.editTableIndex[i] = result;
          return;
        }
      }
      this.editTableIndex.push(result);
    },
    currentPageChange(e) {
      this.param.queryRequest.pageNum = e;
      this.initData();
    }
  },
  watch: {}
};
</script>
<style scoped>
.el-table /deep/.el-checkbox__inner {
  width: 20px;
  height: 20px;
}
.el-table /deep/.el-checkbox__inner::after {
  height: 10px;
  left: 6px;
}
.el-table /deep/.DisabledSelection .cell .el-checkbox__inner {
  display: none;
  position: relative;
}
.el-table /deep/.DisabledSelection .cell:before {
  content: "选择";
  position: absolute;
  right: 40px;
}
</style>